﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using HtmlAgilityPack;

namespace Daroctrius.WebTV
{
    public class BaseHandler : IHttpHandler
    {
        private XmlElement CreateNameValueElement(XmlDocument doc, string name, string value)
        {
            XmlElement element;

            element = doc.CreateElement(name);
            element.InnerText = value;

            return element;
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public static HtmlDocument LoadHtmlDocument(string url)
        {
            HtmlWeb web;

            web = new HtmlWeb();
            web.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2;)";

            return (HtmlDocument)web.Load(url);
        }

        public void ProcessRequest(HttpContext context)
        {
            Type type;
            object obj;
            MethodInfo method;
            Items items;
            XmlSerializer serializer;

            if (String.IsNullOrEmpty(this.Request["m"]))
            {
                items = new Items();
                
                items.Add(new Item()
                {
                    ContentUrl = "/tele-quebec.ashx?m=GetCategories",
                    Name = "Télé Québec",
                    ThumbnailUrl = "/imgs/tele-quebec.png"
                });
            }
            else
            {
                type = this.GetType();
                obj = Activator.CreateInstance(type);
                method = type.GetMethod(this.Request["m"]);
                items = (Items)method.Invoke(obj, null);
            }

            Response.ContentType = "text/xml";
            serializer = new XmlSerializer(typeof(List<Item>), new XmlRootAttribute("Items"));
            serializer.Serialize(this.Response.OutputStream, items.OrderBy(i => i.Name).ToList());
        }

        public HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }

        public HttpResponse Response
        {
            get { return HttpContext.Current.Response; }
        }
    }
}